<template>
  <div class="article-container">
    <div class="box"></div>
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="statusCode === 1">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-if="statusCode === 2">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ articleInfo.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="articleInfo.aut_photo"
          />
          <div slot="title" class="user-name">{{ articleInfo.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ articleInfo.pubdate | relativeTime }}
          </div>
          <!-- <a href="" @click="run($event)">1111111111111111111111</a> -->
          <!-- 关注组件 -->
          <!-- 自定义事件绑定的事件函数的$event是子组件传递出来的数据 -->
          <!-- <follow-user
            :author-id="articleInfo.aut_id"
            :value="articleInfo.is_followed"
            @input="articleInfo.is_followed = $event"
          /> -->
          <!-- 场景：
            儿子既要用父的某个数据(父子==>props==>自定义属性名必须叫做value)；
            又要改父的该数据(子父==>自定义事件==>事件名必须叫做input) 
            <组件 :value="变量"   @input="变量 = $event " />
            <组件 v-model="变量"   />
          -->
          <follow-user
            :author-id="articleInfo.aut_id"
            v-model="articleInfo.is_followed"
          />
          <!-- /关注组件 -->
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          ref="content"
          class="article-content markdown-body"
          v-html="articleInfo.content"
        ></div>
        <van-divider>正文结束</van-divider>

        <!------------------------------ 文章评论列表-------------------------------------->
        <comment-list
          @sendTotal="totalCommentCount = $event"
          :source-id="articleInfo.art_id"
          :list="commentList"
          @replyHandler="replyHandler"
        />
        <!------------------------------ /文章评论列表 ------------------------------------->
        <!------------------------------ 发布文章评论-------------------------------------->
        <van-popup v-model="isPostShow" position="bottom">
          <comment-post
            @postSuccess="postSuccess"
            :target-id="articleInfo.art_id"
          />
        </van-popup>
        <!------------------------------ 发布文章评论-------------------------------------->

        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            class="comment-btn"
            @click="isPostShow = true"
            type="default"
            round
            size="small"
            >写评论</van-button
          >
          <van-icon name="comment-o" :badge="totalCommentCount" color="#777" />
          <!-- 收藏组件 -->
          <!-- <collect-article
            :value="articleInfo.is_collected"
            @input="articleInfo.is_collected = $event"
            :articleId="articleInfo.art_id"
          /> -->
          <collect-article
            v-model="articleInfo.is_collected"
            :articleId="articleInfo.art_id"
          />
          <!-- /收藏组件 -->
          <!-- 一个组件只能有一个v-model -->
          <!-- 点赞组件 -->
          <!-- <zan-article
            :is-attitude="articleInfo.attitude"
            @update:isAttitude="articleInfo.attitude = $event"
            :articleId="articleInfo.art_id"
          /> -->
          <!-- 
            场景： v-model一样的场景
            <组件 :自定义属性名="变量" @update:自定义属性名="变量=$event" />
            <组件 :自定义属性名.sync="变量"/>
           -->
          <zan-article
            :is-attitude.sync="articleInfo.attitude"
            :articleId="articleInfo.art_id"
          />
          <!-- /点赞组件 -->
          <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-if="statusCode === 4">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-if="statusCode === 3">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="initData">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

    <!-- 评论回复 -->
    <van-popup position="bottom" v-model="isReplyShow" style="height: 100vh">
      <comment-reply
        :comment-data="currentComment"
        v-if="isReplyShow"
        @close="isReplyShow = false"
      />
    </van-popup>
    <!-- /评论回复 -->
  </div>
</template>

<script>
/*
条件渲染思路：
  页面打开  等待中  loading:true
  加载数据结束   loading:false
    ===> 加载失败     加载失败   资源不存在
    ===> 加载成功     正常显示
*/
import { getArticleInfoApi } from "@/api/Article";
import { ImagePreview } from "vant";
// console.log(ImagePreview);
// ImagePreview({images:图片数组,startPosition:开始位置 })
import FollowUser from "@/components/follow-user";
import CollectArticle from "@/components/collect-article";
import ZanArticle from "@/components/zan-article";
import CommentList from "./components/comment-list";
import CommentPost from "./components/comment-post";
import CommentReply from "./components/comment-reply";
export default {
  name: "ArticleIndex",
  components: {
    FollowUser,
    CommentPost,
    CollectArticle,
    ZanArticle,
    CommentList,
    CommentReply,
  },
  data() {
    return {
      // 1. data定义变量
      articleInfo: {},
      articleId: this.$route.params.id,
      statusCode: 1, // 1 加载中  2 表示加载成功   3 表示加载失败   4 表示资源不存在
      totalCommentCount: "",
      isPostShow: false,
      commentList: [], // 文章评论
      isReplyShow: false,
      currentComment: {},
    };
  },
  provide() {
    return {
      // 提供给后代的数据
      articleId: this.articleId, // 这里不要写this.articleInfo.art_id
    };
  },
  created() {
    // 3. 调用方法
    this.initData();
  },
  methods: {
    // 2. 定义方法
    async initData() {
      this.statusCode = 1; // 这句代码是给重新加载的时候使用的！
      try {
        // 2.1 发送请求
        //   配置路由  path:"/article/:id"
        //   书写路径    to="/article/200"
        //
        //   console.log(this.$route);  // 当前页面的路由信息
        // this.$route.params 是动态路由的数据    /article/200
        // this.$route.query 是查询参数          /article?id=200
        let { data } = await getArticleInfoApi(this.articleId);
        //   2.2 赋值
        this.articleInfo = data.data;
        this.statusCode = 2;
        // document.querySelectorAll("img")  // 找到网页中所有的img节点
        // document.querySelector(".article-content").querySelectorAll("img")
        // this.$refs.content.querySelectorAll("img")
        // 读取不到的因为页面渲染是需要耗时的
        // console.log(this.$refs.content);
        // console.log(document.querySelector(".article-content"));
        // 等到页面渲染完成之后
        this.$nextTick(() => {
          // 1. 找到文章正文中的所有图片标签
          const imageNodes = this.$refs.content.querySelectorAll("img");
          // 2. 将图片标签的地址组合成一个数组
          const imgSrc = Array.from(imageNodes).map((item) => item.src);
          // 3. 给每个图片标签绑定点击事件，调用预览函数，传入点击项的索引
          imageNodes.forEach((img, idx) => {
            img.onclick = function () {
              ImagePreview({ images: imgSrc, startPosition: idx });
            };
          });
        });
      } catch (error) {
        if (error.response && error.response.status === 404) {
          this.statusCode = 4;
        } else {
          this.statusCode = 3;
        }
        console.log(error);
      }
    },
    // updateFollow(val) {
    //   this.articleInfo.is_followed = val;
    // },
    // run(event) {
    //   event.preventDefault();
    //   console.log(event);
    // },
    postSuccess(val) {
      // val 是 comment-post组件传递过来的新增成功的数据
      // 将成功的数据放入commnet-list里面的list数组中，其实只需要放在
      // index.vue组件的commentList变量就可以
      this.commentList.unshift(val);
      this.isPostShow = false;
      this.totalCommentCount++;
    },
    replyHandler(val) {
      // val就是点击行的评论数据
      console.log(val);
      this.currentComment = val;
      this.isReplyShow = true;
    },
  },
};
</script>

<style scoped lang="less">
// 导入css文件
// @import url(); // 原生
@import "@/styles/github-markdown.css"; // less里写法，一定要有分号
.article-container {
  .van-nav-bar {
    background-color: #5094f3;
  }
  /deep/ .van-nav-bar__title {
    color: #fff;
  }
  /deep/ .van-nav-bar .van-icon {
    color: #fff;
  }
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
